<?php

namespace App\Http\Controllers;

use App\Services\CartService;
use Illuminate\Http\Request;
use App\Http\Requests\AddCartRequest;
use App\Models\ProductSku;

class CartController extends Controller
{
    protected $cartService;

    //利用Laravel自动解析功能注入CartService类
    public function __construct(CartService $cartService)
    {
        $this->cartService = $cartService;
    }

    public function index(Request $request)
    {
        $cartItems = $this->cartService->get();
        $address = $request->user()->addresses()->orderby('last_used_at','desc')->get();

        return view('cart.index',['cartItems'=>$cartItems,'addresses'=>$address]);
    }

    //
    public function add(AddCartRequest $request)
    {
        $skuId = $request->input('sku_id');
        $amount = $request->input('amount');

        //封装业务代码
        //从数据库中查询该商品是否已经在购物车
        //$user = $request->user();
        //if($cart = $user->cartItems()->where('product_sku_id',$skuId)->first()){
        //    //如果存在在直接叠加商品数量
        //    $cart->update([
        //        'amount' => $cart->amount + $amount
        //    ]);
        //}else{
        //    //否则创建一个新的购物车
        //    $cart = new CartItem(['amount'=>$amount]);
        //    $cart->user()->associate($user);
        //    $cart->productSku()->associate($skuId);
        //    $cart->save();
        //}
        $this->cartService->add($skuId,$amount);

        return [];
    }

    public function remove(ProductSku $sku,Request $request)
    {
        //封装业务代码
        //$request->user()->cartItems()->where('product_sku_id', $sku->id)->delete();
        $this->cartService->remove($sku->id);

        return [];
    }

}
